﻿<%@ WebHandler Language="C#" Class="ProductTeamInfoMaintPageHandler" %>

/* Description:件号单元关联维护后端接口
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2024.12.10
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BusinessRule.DTO;
using DatabaseAccess.DBUtility;
using System.Web.SessionState;
using Newtonsoft.Json;
using System.Collections;
using System.IO;
using System.Configuration;

public class ProductTeamInfoMaintPageHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo = new CurrentUserInfo();
    string exportPath = ConfigurationManager.AppSettings["ExportPath"]; //导出路径
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getUserInfo":
                    getUserInfo(context);
                    break;
                case "getWorkcenter":
                    getWorkcenter(context);
                    break;
                case "getTeam":
                    getTeam(context);
                    break;
                case "getData":
                    getData(context);
                    break;
                case "addData":
                    addData(context);//添加
                    break;
                case "changeTeam":
                    changeTeam(context);//更改单元
                    break;
                case "changeIsuse":
                    changeIsuse(context);//启用/停用
                    break;
                case "exportExcel":
                    exportExcel(context);//导出
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result));
        }
    }

    void getWorkcenter(HttpContext context)
    {
        string sql = @"SELECT w.workcenterid,w.workcentername FROM workcenter w";
        if (context.Request["factoryid"] != null && context.Request["factoryid"].ToString() != "")
        {
            sql += string.Format(" WHERE w.factoryid = '{0}'", context.Request["factoryid"].ToString());
        }
        DataTable result = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in result.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "获取成功", DBTable = result }));
    }

    void getTeam(HttpContext context)
    {
        string sql = @"SELECT t.teamid,t.teamname FROM team t";
        if (context.Request["workcenterid"] != null && context.Request["workcenterid"].ToString() != "")
        {
            sql += string.Format(" WHERE t.workcenterid = '{0}'", context.Request["workcenterid"].ToString());
        }
        DataTable result = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in result.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "获取成功", DBTable = result }));
    }

    //生成查询sql
    string getQuerySql(HttpContext context)
    {
        string sql = @"
SELECT t.id,t.productname,p.description,f.factoryname,w.workcentername,w.workcenterid,te.teamname,t.teamid,DECODE(t.isuse,1,'停用','启用') isuse,
       t.createdate,e.fullname createemp,
       e2.fullname lastchangeemp,t.lastchangedate
FROM productteaminfo t
LEFT JOIN productbase pb ON pb.productname = t.productname
LEFT JOIN product p ON p.productid = pb.revofrcdid
LEFT JOIN employee e ON e.employeeid = t.createemployeeid
LEFT JOIN employee e2 ON e2.employeeid = t.lastchangeemployeeid
LEFT JOIN team te ON te.teamid = t.teamid
LEFT JOIN workcenter w ON w.workcenterid = te.workcenterid
LEFT JOIN factory f ON f.factoryid = w.factoryid
WHERE 1=1 ";
        //件号
        if (context.Request["productname"] != null && context.Request["productname"].ToString() != "")
        {
            sql += string.Format(" AND t.productname LIKE '%{0}%'", context.Request["productname"].ToString());
        }

        //分厂
        if (context.Request["factoryid"] != null && context.Request["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND te.factoryid = '{0}'", context.Request["factoryid"].ToString());
        }

        //工区
        if (context.Request["workcenterid"] != null && context.Request["workcenterid"].ToString() != "")
        {
            sql += string.Format(" AND te.workcenterid = '{0}'", context.Request["workcenterid"].ToString());
        }

        //班组
        if (context.Request["teamid"] != null && context.Request["teamid"].ToString() != "")
        {
            sql += string.Format(" AND t.teamid = '{0}'", context.Request["teamid"].ToString());
        }

        //创建人
        if (context.Request["createEmp"] != null && context.Request["createEmp"].ToString() != "")
        {
            sql += string.Format(" AND e.fullname like '%{0}%'", context.Request["createEmp"].ToString());
        }

        //状态
        if (context.Request["status"] != null && context.Request["status"].ToString() != "请选择")
        {
            sql += string.Format(" AND t.isuse = '{0}'", context.Request["status"].ToString());
        }
        return sql;
    }

    void getUserInfo(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", ReturnData = m_UserInfo }));
        }
    }

    void getData(HttpContext context)
    {
        string sql = getQuerySql(context);
        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
        paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        foreach (DataColumn col in result.DBTable.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    //添加
    void addData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
            return;
        }
        string productname = context.Request.Form["productname"].ToString().Trim();
        string teamid = context.Request.Form["teamid"].ToString();
        string sql = string.Format("SELECT * FROM productbase pb WHERE pb.productname = '{0}'", productname);
        DataTable dtProduct = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtProduct.Rows.Count == 0)
        {
            string msg = string.Format("件号: {0} 不存在。", productname);
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = msg, DBTable = null }));
            return;
        }
        sql = string.Format("SELECT * FROM productteaminfo t WHERE t.productname = '{0}'", productname);
        DataTable dtExist = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtExist.Rows.Count > 0)
        {
            string msg = string.Format("件号: {0} 已存在，不能添加。", productname);
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = msg, DBTable = null }));
            return;
        }
        string insertSql = @"
INSERT INTO productteaminfo(createdate,createemployeeid,id,isuse,productname,teamid)
VALUES(SYSDATE,'{0}','{1}',0,'{2}','{3}')";
        insertSql = string.Format(insertSql, m_UserInfo.EmployeeID, Guid.NewGuid().ToString(), productname, teamid);
        DatabaseHelper.ExecuteSql(insertSql);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "添加成功", DBTable = null }));
    }

    //更新单元成功
    void changeTeam(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        string teamid = context.Request.Form["teamid"].ToString();
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
        ArrayList sqlList = new ArrayList();
        foreach (DataRow dr in dtPostData.Rows)
        {
            string id = dr["id"].ToString();
            string updateSql = @"UPDATE productteaminfo t
                           SET t.teamid = '{1}',
                               t.lastchangedate = sysdate,
                               t.lastchangeemployeeid = '{2}'
                           WHERE t.id = '{0}'";
            updateSql = string.Format(updateSql, id, teamid, m_UserInfo.EmployeeID);
            sqlList.Add(updateSql);
        }
        Boolean isSuccess = DatabaseHelper.ExecuteSqlListTran(sqlList);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = isSuccess, Message = "更新单元成功", DBTable = null }));
    }

    //启用、停用
    void changeIsuse(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        string isuse = context.Request.Form["isuse"].ToString();
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
        ArrayList sqlList = new ArrayList();
        foreach (DataRow dr in dtPostData.Rows)
        {
            string id = dr["id"].ToString();
            string updateSql = @"UPDATE productteaminfo t
                           SET t.isuse = '{1}',
                               t.lastchangedate = sysdate,
                               t.lastchangeemployeeid = '{2}'
                           WHERE t.id = '{0}'";
            updateSql = string.Format(updateSql, id, isuse, m_UserInfo.EmployeeID);
            sqlList.Add(updateSql);
        }
        Boolean isSuccess = DatabaseHelper.ExecuteSqlListTran(sqlList);
        string msg = isuse == "0" ? "启用" : "停用" + "成功";
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = isSuccess, Message = msg, DBTable = null }));
    }

    //导出
    void exportExcel(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "导出成功" };
        string sql = getQuerySql(context);

        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);

        if (dt.Rows.Count == 0)
        {
            result = new uMESProcessResult() { Result = false, Message = "没有数据不能导出" };
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
        else
        {
            dt.Columns.Remove("id");
            dt.Columns.Remove("teamid");
            dt.Columns.Remove("workcenterid");

            dt.Columns["productname"].ColumnName = "零件号";
            dt.Columns["description"].ColumnName = "零件名称";
            dt.Columns["teamname"].ColumnName = "单元";
            dt.Columns["workcentername"].ColumnName = "中心";
            dt.Columns["factoryname"].ColumnName = "分厂";
            dt.Columns["isuse"].ColumnName = "状态";
            dt.Columns["createdate"].ColumnName = "创建时间";
            dt.Columns["createemp"].ColumnName = "创建人";
            dt.Columns["lastchangeemp"].ColumnName = "更新人";
            dt.Columns["lastchangedate"].ColumnName = "更新时间";

            string fileName = "件号单元维护导出" + DateTime.Now.ToString("yyyyMMddHHmmddssffff") + ".xls";
            string strPath = context.Request.MapPath(exportPath + "CheckItemTem/");
            if (!Directory.Exists(strPath)) //如果没有目录，创建
            {
                Directory.CreateDirectory(strPath);
            }
            strPath += fileName;
            byte[] ms = uLMS_CommonFunction.DataTableExportToExcel(dt, null, null);
            uLMS_CommonFunction.ParseBytesToFile(ms, strPath);
            string url = "http://" + context.Request.Url.Host + context.Request.ApplicationPath + exportPath.Trim('~').Replace("\\", "/") + "CheckItemTem/" + fileName;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("filename", fileName);
            dic.Add("url", url);
            result.ReturnData = dic;
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
}